package ajjj.kiviq.servlets;

import ajjj.kiviq.Constants;
import ajjj.kiviq.entities.UserEnt;
import ajjj.kiviq.helpers.UserHelper;
import ajjj.kiviq.remoteInterfaces.IRemoteUser;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

/**
 * Updated 2011-10-05, Jonatan
 * Added error messages and updated redirects to match
 * the new filter, minor refactoring
 * 
 * Tries to log in the user with the UserController,
 * if successful the username is saved in the session
 * 
 * @author jeklund
 */
@WebServlet(name = "loginServlet", urlPatterns = {Constants.LoginServlet})
public class LoginServlet extends HttpServlet {

    @EJB
    private IRemoteUser uf;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	String action = request.getParameter("action");       
	try {
	    if ("login".equals(action)) {
		String userName = request.getParameter("uName");
		String userPass = request.getParameter("uPwd");

		if (userName != null && userPass != null && !userName.isEmpty() && !userPass.isEmpty()) {

		    if (login(userName, userPass)) {
			HttpSession session = request.getSession();
			session.setAttribute(Constants.User, userName);
		    } else {
			request.getSession().setAttribute(Constants.Message, "Invalid username or password");
		    }
		} else {
		    request.getSession().setAttribute(Constants.Message, "Missing input");
		}

		response.sendRedirect(Constants.Categories);

	    } else if ("register".equals(action)) {
		String userName = request.getParameter("uName");
		String userPass1 = request.getParameter("uPwd1");
		String userPass2 = request.getParameter("uPwd2");

		if ((null != userName) && (null != userPass1) && (null != userPass2)
			&& (!userName.isEmpty()) && (!userPass1.isEmpty()) && (!userPass2.isEmpty())) {
		    if (userPass1.equals(userPass2)) {
			UserEnt newUser = new UserEnt();
			newUser.setName(userName);
			newUser.setPassword(userPass1);
			String result = register(newUser);
			request.getSession().setAttribute(Constants.Message, result);
			if (null != result) {
			    request.getSession().setAttribute(Constants.Message, result);
			} else {
                            response.sendRedirect(Constants.Login);
                            return;
                        }
		    } else {
			request.getSession().setAttribute(Constants.Message, "Passwords must match");
		    }
		} else {
		    request.getSession().setAttribute(Constants.Message, "Missing input");
		}
		response.sendRedirect(Constants.Register);

	    } else if ("logout".equals(action)) {
		request.getSession().invalidate();
		response.sendRedirect(Constants.Login);
	    }

	} catch (Exception e) {
	    request.getSession().setAttribute(Constants.Message, "Failed to register or login user");
	    response.sendRedirect(Constants.Login);
	} finally {
	}
    }
    
    private String register(UserEnt user) {
        try {
            if (uf.findUser(user.getName()) == null) {
                user.setPassword(UserHelper.toMD5(user.getPassword()));
                uf.addUser(user);
            } else {
                return "A user with the specified username already exists";
            }

            return null;
        } catch (Exception e) {
            return "Failed to register user";
        }
    }
    
    private boolean login(String userName, String password) {
        try {

            UserEnt u = uf.findUser(userName);
            String md5 = UserHelper.toMD5(password);

            if (u.getPassword().equals(md5)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
	return "Short description";
    }// </editor-fold>
}
